const express = require("express");
const router = express.Router();
const { Chapters, Course } = require("../../models");

const { success, failure } = require("../../utils/response");
const {NotFound} = require('http-errors');
const { Op, where } = require("sequelize");

// 查询所有章节信息
router.get("/", async (req, res) => {
  try {
    const query = req.query;

    const pageIndex = Math.abs(Number(query.pageIndex)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (pageIndex - 1) * pageSize;

    const condition = {
      ...getCondition(),
      order: [["id", "DESC"]],
      limit: pageSize,
      offset,
    };

    const { count, rows } = await Chapters.findAndCountAll(condition);
    const data = {
      pagination: {
        total: count,
        pageIndex,
        pageSize,
      },
      data: rows,
    };
    success(res, "列表查询成功", data);
  } catch (error) {
    failure(res, error);
  }
});

// 新增章节接口
router.post("/", async (req, res) => {
  try {
    const body = filterBody(req);
    // 创建章节，并增加章节章节数
    const chapter = await Chapters.create(body);
    await Course.increment('ChaptersCount',{where:{id:chapter.courseId}});
    
    success(res, "添加成功！", {chapter},201);
  } catch (error) {
    failure(res, error);
  }
});

// 删除章节接口
router.delete("/:id", async (req, res) => {
  try {
    const chapter = await getChapter(req);
    // 删除章节，并减少章节章节数
    await chapter.destroy();
    await Course.decrement('ChaptersCount',{where:{id:chapter.courseId}});
    success(res, "删除章节成功", null);
  } catch (error) {
    failure(res, error);
  }
});

// 修改章节信息
router.put("/:id", async (req, res) => {
  try {
    const body = await filterBody(req);
    const chapter = await getChapter(req);
    await chapter.update(body);
    success(res, "更新信息成功", chapter);
  } catch (error) {
    failure(res, error);
  }
});

// 章节模糊搜索
router.get("/search", async (req, res) => {
  try {
    const query = req.query;

    const pageIndex = Math.abs(Number(query.pageIndex)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (pageIndex - 1) * pageSize;

    const condition = {
      ...getCondition(),
      where:{},
      order: [["rank","ASC"],["id", "DESC"]],
      limit: pageSize,
      offset,
    };
    if (query.title) {
      condition.where.title = {
        [Op.like]: `%${query.title}%`,
      }
    }

    const { count, rows } = await Chapters.findAndCountAll(condition);

    const data = {
      pagination: {
        total: count,
        pageIndex,
        pageSize,
      },
      data: rows,
    };
    success(res, "查询成功", data);
  } catch (error) {
    failure(res, error);
  }
});

// 查询章节详细信息
router.get("/:id", async (req, res) => {
  try {
    const chapter = await getChapter(req);
    success(res, "获取详情成功", chapter);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 公共方法：过滤请求体
 * @param {*} req
 * @returns
 */
function filterBody(req) {
  console.log("body", req.body);
  const {
    courseId,
    title,
    content,
    video,
    rank,
  } = req.body;
  return {
    courseId,
    title,
    content,
    video,
    rank,
  };
}

/**
 * 公共方法：获取章节
 * @param {*} req
 * @returns
 */
async function getChapter(req) {
  const { id } = req.params;
  const condition = getCondition();
  const chapter = await Chapters.findByPk(id, condition);
  if (!chapter) {
    throw new NotFound("该章节不存在");
  }
  return chapter;
}

/**
 * 公共方法：关联分类、用户数据
 * @returns {{include: [{as: string, model, attributes: string[]}], attributes: {exclude: string[]}}}
 */
function getCondition() {
  return {
    attributes: { exclude: ["courseId","CourseId"] },
    include: [
      {
        model: Course,
        as: "course",
        attributes: ["id", "name"],
      },
    ],
  };
}

module.exports = router;
